#coding=utf8
import os
import sys
import logging

import click

from cronic.cronfile import Cronfile
from cronic.exceptions import *
from cronic.edit import delete_segment, update_segment


@click.command()
@click.option('-c', '--clear', is_flag=True, help=u'删除crontab')
@click.option('-u', '--update', is_flag=True, help=u'更新crontab')
@click.argument('fpath')
@click.argument('kvs', nargs=-1)
def cli(clear, update, fpath, kvs):
    logging.basicConfig(level=logging.DEBUG)

    try:
        cli_kwargs = dict(pair.split('=') for pair in kvs if len(pair) > 0)
    except ValueError:
        logging.error(u'附加kv参数格式错误')
        sys.exit(-1)

    cronfile = Cronfile(cli_kwargs, fpath)
    try:
        cronfile.parse()
    except CompileError as ex:
        logging.error(u'语法错误：{}'.format(ex))
        sys.exit(-1)

    for line in cronfile.generate():
        print line

    if clear:
        delete_segment(cronfile)
        logging.info("删除成功")
    elif update:
        update_segment(cronfile)
        logging.info("更新成功")


def main():
    cli()


if __name__ == '__main__':
    main()
